﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CtCache;
using CtCommon.Utility;
using Cxx.BLL;
using Cxx.Common;
using Cxx.Entity;

namespace Cxx.OrderManagerSys
{
    public partial class StockRecordManage : System.Web.UI.Page
    {
        private static readonly int dayslimit = ConfigurationManager.AppSettings["exportDays"].ToInt32();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDdlStockType();
                BindData();
            }
        }

        private void BindData()
        {
            string condition = MyWebHelper.SelectKey(pnlSearch, out _);
            var list = StockRecord.GetListForPage(condition, pager.CurrentPageIndex, pager.PageSize, out int recordCount);
            pager.RecordCount = recordCount;
            rptOrderList.DataSource = list;
            rptOrderList.DataBind();
        }

        protected void btBrowse_Click(object sender, EventArgs e)
        {
            pager.CurrentPageIndex = 1;
            BindData();
        }

        protected void btExport_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtStartTime.Text) || string.IsNullOrWhiteSpace(txtEndTime.Text))
            {
                JScript.Alert(Page, "导出时需要选择起始时间和结束时间");
                return;
            }
            DateTime startTime = txtStartTime.Text.ToDateTime();
            DateTime endTime = txtEndTime.Text.ToDateTime();
            int days = (int)(endTime - startTime).TotalDays + 1;
            if (days > dayslimit)
            {
                JScript.Alert(Page, $"导出的时间范围不得超过 {dayslimit} 天");
                return;
            }
            string condition = MyWebHelper.SelectKey(pnlSearch, out _);
            string key = Guid.NewGuid().ToString().Replace("-", "");
            CacheHelper.Instance.AddObject(key, condition);
            string url = $"http://{Request.Url.Host}:{Request.Url.Port}/StockRecordExport.aspx?Guid={key}";
            JScript.RedirectInNewWindow(Page, url);
        }

        protected void pager_OnPageChanged(object sender, EventArgs e)
        {
            BindData();
        }

        public string GetStockTypeDesc(string num)
        {
            int typeInt = num.ToInt32();
            return ((StockTypes) typeInt).GetDescription();
        }

        private void BindDdlStockType()
        {
            var dic = EnumHelper.GetTypeItemList<StockTypes>().ToDictionary(p => p.Value, o => o.Description);
            
            ddlStockType.DataSource = dic;
            ddlStockType.DataTextField = "Value";
            ddlStockType.DataValueField = "Key";
            
            ddlStockType.DataBind();
            ddlStockType.Items.Insert(0, new ListItem("请选择", ""));
        }
    }
}